<?php

namespace app\common\lib\Ai\model;

use app\common\lib\Ai\Contract;
use app\common\lib\Ai\OpenApi;
use app\common\lib\Common;
use app\common\lib\GuzzleNew;
use app\exception\IndexException;

class QwenOpenApi implements Contract
{

    const BASE_URL = "http://47.98.193.77:8006/";
    const FENJIN_BASE_URL = "http://47.98.193.77:8009/";

    /**
     * @param $content
     * @param $aiCommand
     * @return mixed
     * @throws IndexException
     */
    public function chat($content, $aiCommand = '')
    {
        $param = [
            'system_prompt' => $aiCommand,
            'message_prompt' => $content,
        ];

        $header = [
            'Content-Type' => 'application/json',
        ];
        $guzzle = (new GuzzleNew(300));
        $result = $guzzle->post(self::BASE_URL, 'openapi/chat', $param, $header);

        //记录请求日记
        $contentText = "\n指令----------------------------------\n" . $aiCommand . "\nparam: ----------------------------------\n" .
            json_encode($param, 256) . "\nresult----------------------------------\n" . json_encode($result, 256) . "\n\n";

        Common::createAndSaveLog($contentText, 'qwen_api');
        if (!empty($result['content'])) {
            return $result['content'];
        } elseif (!empty($result['error_code']) && $result['error_code'] != 0) {
            throw new IndexException(4020, ($result['message']));
        }
        throw new IndexException(4020, $guzzle->getError());
    }

    /**
     * 根据短文本生成长文本，一次传40个
     * @throws IndexException
     */
    public function partsLongText($content, string $aiCommand = '', $role_dict = []): array
    {
        $aiCommand = $aiCommand ?: getAiCommand('long_content_parts_ai_command');

        $param = [
            'url' => self::BASE_URL . '/openapi/chat',
            'system_prompt' => $aiCommand,
            'passage' => $content,
            'role_dict' => !empty($role_dict) ? $role_dict : new \stdClass(),
        ];

        $header = [
            'Content-Type' => 'application/json',
        ];
        $guzzle = (new GuzzleNew(300));
        $result = $guzzle->post(self::FENJIN_BASE_URL, 'openapi/fenjin', $param, $header);

        //记录请求日记
        $contentText = "\n指令 long_content_parts_ai_command----------------------------------\n" . $aiCommand . "\nparam: ----------------------------------\n" .
            json_encode($param, 256) . "\nresult----------------------------------\n" . json_encode($result, 256) . "\n\n";

        Common::createAndSaveLog($contentText, 'qwen_api');
        if (!empty($result['new_contents'])) {
            $content = explode("\n", $result['new_contents']);
            return ["content" => array_values(array_filter($content)), "role_dict" => $result['role_dict']];
        } elseif (!empty($result['error_code']) && $result['error_code'] != 0) {
            throw new IndexException(4020, ($result['message']));
        }
        throw new IndexException(4020, $guzzle->getError());
    }


    /**
     * 通过小说章节把内容分段 - 废弃
     * @param $content
     * @return mixed
     * @throws IndexException
     */
    public function generatedChapter($content)
    {

        return $this->chat($content);
    }

    /**
     * 生成中文描述词 - 废弃
     * @param $content
     * @param string $aiCommand
     * @return mixed
     * @throws IndexException
     */
    public function generatedDescWork($content, $aiCommand = '')
    {

        $aiCommand == false && $aiCommand = config('param.analyze_content_ai_command', '分析该段内容，不超过50个字：@content');

        return $this->chat($content, $aiCommand);
    }

    /**
     * 改编文章内容
     * @param $content
     * @param string $aiCommand
     * @param string $lang
     * @return mixed
     * @throws IndexException
     */
    public function generatedContent($content, $aiCommand, $lang = '')
    {

        return $this->chat($content, $aiCommand);
    }

    /**
     * 批量生成英文描述词
     * @param $content
     * @param string $aiCommand
     * @param string $gptVersion
     * @return mixed
     * @throws IndexException
     */
    public function generatedBatchPrompt($content, $aiCommand = '', $gptVersion = '')
    {

        $aiCommand == false && $aiCommand = getAiCommand('new_batch_prompt_ai_command');

        return $this->chat($content, $aiCommand);
    }

    /**
     * 生成英文描述词
     * @param $content
     * @param $aiCommand
     * @return mixed
     * @throws IndexException
     */
    public function generatedImagePrompt($content, $aiCommand = '')
    {

        $aiCommand == false && $aiCommand = config('param.prompt_ai_command', '');

        return $this->chat($content, $aiCommand);
    }

    /**
     * 给用户文章内容通过ai分段
     * @param $content
     * @return array
     * @throws IndexException
     */
    public function aiContentPartsToUser($content)
    {
        $content = str_replace(["\n", "\r", '"', '“', '”', '[', ']', '【', '】', '「', '」', '^'], "", $content);

        $aiCommand = getAiCommand('new_content_parts_ai_command');

        $content = $this->chat($content, $aiCommand);

        return array_values(array_filter(explode("\n", $content)));
    }

}